<template>
  <div class="login pageFlexColumn pageAlignEnd">
    <div class="loginContent pageFlexColumn pageFlexCenter">
      <div class="pageFlex pageAlignCenter" style="width: 61%;">
        <img src="@/assets/logo/logo_fang.png" alt="易创燃气" class="logo">
        <div class="title">易创燃气智慧管理平台</div>
      </div>
      <div class="loginText">欢迎登录</div>
      <el-form class="formBox" ref="loginRef" :model="loginForm" :rules="loginRules">
        <el-form-item class="partBox bgFF" prop="username">
          <el-input class="input" type="text" size="large" auto-complete="off" placeholder="请输入账号" v-model="loginForm.username">
            <template #prefix>
              <img src="../assets/images/login_user.png" alt="账号" class="icon">
            </template>
          </el-input>
        </el-form-item>
        <el-form-item class="partBox bgFF" prop="password">
          <el-input class="input" :type="showPwd ? 'text' : 'password'" size="large" auto-complete="off" placeholder="请输入密码" 
            v-model="loginForm.password" @keyup.enter="handleLogin">
            <template #prefix>
              <img src="../assets/images/login_lock.png" alt="密码" class="icon">
            </template>
            <template #suffix>
              <div class="pwdIcon" :class="{'active': showPwd}" @click="showPwd = !showPwd">
                <img src="../assets/images/login_pwdShow.png" alt="密码" class="icon icon1"/>
                <img src="../assets/images/login_pwd.png" alt="密码" class="icon icon2"/>
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item class="partBox bgFF pageFlex" prop="code" v-if="captchaEnabled">
          <el-input class="input" size="large" auto-complete="off" placeholder="请输入验证码"
            v-model="loginForm.code" @keyup.enter="handleLogin">
            <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon"/></template>
          </el-input>
          <div class="loginCode pageFlex pageFlexCenter">
            <img class="img" :src="codeUrl" @click="getCode"/>
          </div>
        </el-form-item>
        <div class="pageFlex pageAlignCenter pageSpaceBetween" style="width: 100%;margin-top: 18px;">
          <el-checkbox v-model="loginForm.rememberMe" style="height: 20px;">记住我</el-checkbox>
          <!-- <div class="forgetPwd">忘记密码?</div> -->
          <router-link class="forgetPwd" :to="'/register'">注册</router-link>
        </div>
        <el-form-item style="width: 100%;margin-top: 41px;">
          <el-button size="large" type="primary" class="btnBox"
            :loading="loading" @click.prevent="handleLogin">
            <span class="btnText">{{loading ? '登 录 中...' : '登 录'}}</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login";
import { getRouters } from "@/api/menu";
import Cookies from "js-cookie";
import { encrypt, decrypt, loginEncrypt } from "@/utils/jsencrypt";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "admin",//admin
  password: "admin123",//admin123
  rememberMe: false,
  code: "",
  uuid: "",
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

const showPwd = ref(false);
const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);
const status = ref(0);
const newPath = ref(null);
function handleLogin() {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), {
          expires: 30,
        });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      let obj = JSON.parse(JSON.stringify(loginForm.value));
      // obj.password = loginEncrypt(obj.password);
      // 调用action的登录方法
      userStore.login(obj)
        .then(() => {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          // 获取当前用户的路由权限
          getRouters().then((res) => {
            res.data.map((item) => {
              if(item.children){
                item.children.map((child) => {
                  if (child.path == "index") {
                    status.value = 1;
                  }
                });
              }
            });
            const currentData = res.data[0];
            // 有首页权限就登录进首页 没有就登录进路由第一个页面
            if (status.value === 1) {
              router.push({
                path: redirect.value || "/",
                query: otherQueryParams,
              });
            } else {
              newPath.value =
                currentData.path + "/" + currentData.children[0].path;
              router.push({
                path: newPath.value,
              });
            }
          });
        })
        .catch(() => {
          loading.value = false;
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }
        });
    }
  });
}

function getCode() {
  getCodeImg().then((res) => {
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}

getCode();
getCookie();
</script>
<style lang="scss" scoped>
@import "@/assets/styles/public.scss";
.login{
  width: 100%;
  height: 100vh;
  background-image: url('../assets/images/login_bg.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  overflow: hidden;
  .loginContent{
    width: 50%;
    height: 100%;
    .logo{
      width: 56px;
      height: 56px;
      display: block;
    }
    .title{
      margin-left: 14px;
      height: 48px;
      font-weight: 500;
      font-size: 24px;
      color: #0A1B39;
      line-height: 48px;
      text-shadow: 0px 4px 4px rgba(190,190,190,0.46);
    }
    .loginText{
      margin-top: 20px;
      width: 61%;
      height: 44px;
      font-weight: 400;
      font-size: 35px;
      color: #0A1B39;
      line-height: 44px;
    }
    .formBox{
      width: 61%;
      margin-top: 16px;
      .partBox{
        width: 100%;
        height: 44px;
        border-radius: 6px;
        margin: 24px 0 0 0;
        flex-wrap: nowrap;
        .input{
          width: 100%;
          height: 100%;
          flex: 1;
          :deep(.el-input__wrapper){
            box-shadow: none;
          }
          .icon{
            width: 15px;
            height: 15px;
          }
          .pwdIcon{
            cursor: pointer;
            .icon1{
              display: none;
            }
            .icon2{
              display: block;
            }
            &.active{
              .icon1{
                display: block;
              }
              .icon2{
                display: none;
              }
            }
          }
        }
        .loginCode{
          width: auto;
          height: 100%;
          cursor: pointer;
          .img{
            width: 100%;
            height: 100%;
          }
        }
      }
      .forgetPwd{
        height: 20px;
        font-weight: 400;
        font-size: 14px;
        color: #165DFF;
        line-height: 20px;
        cursor: pointer;
        user-select: none;
      }
      .btnBox{
        width: 100%;
        height: 53px;
        background: #165DFF;
        border-radius: 6px;
        .btnText{
          font-weight: 500;
          font-size: 20px;
          color: #FFFFFF;
        }
      }
    }
  }
}
</style>
